package moriarty.gwt.client;

import moriarty.gwt.shared.Group;

import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class MemberFieldUpdater implements FieldUpdater<Group, Boolean> {

	private final SotdServiceAsync sotdService = GWT.create(SotdService.class);
	
	@Override
	public void update(int index, final Group group, Boolean value) {
        if (value) {
            group.members.add(CurrentUser.getInstance().getCurrentUserEmail());
            CurrentUser.getInstance().getCurrentUser().groups.add(group.groupName);
            sotdService.updateDataStoreObject(group, new AsyncCallback<Void>(){
				public void onFailure(Throwable caught) {
					System.out.println("Datastore could not add " + CurrentUser.getInstance().getCurrentUserEmail() + " from " + group.groupName);
				}
				public void onSuccess(Void result) {
					System.out.println("Datastore added " + CurrentUser.getInstance().getCurrentUserEmail() + " from " + group.groupName + " successfully!");
				}          	
            });
            sotdService.updateDataStoreObject(CurrentUser.getInstance().getCurrentUser(), new AsyncCallback<Void>(){
				public void onFailure(Throwable caught) {
					System.out.println("Datastore could not add " + group.groupName + " to " + CurrentUser.getInstance().getCurrentUserEmail() );
				}
				public void onSuccess(Void result) {
					System.out.println("Datastore added " + group.groupName + " to " +  CurrentUser.getInstance().getCurrentUserEmail() + " successfully!");
				}          	
            });
        } else {
            group.members.remove(CurrentUser.getInstance().getCurrentUserEmail());
            CurrentUser.getInstance().getCurrentUser().groups.remove(group.groupName);
            sotdService.updateDataStoreObject(group, new AsyncCallback<Void>(){
				public void onFailure(Throwable caught) {
					System.out.println("Datastore could not remove " + CurrentUser.getInstance().getCurrentUserEmail() + " from " + group.groupName);
				}
				public void onSuccess(Void result) {
					System.out.println("Datastore removed " + CurrentUser.getInstance().getCurrentUserEmail() + " from " + group.groupName + " successfully!");
				}          	
            });       
            sotdService.updateDataStoreObject(CurrentUser.getInstance().getCurrentUser(), new AsyncCallback<Void>(){
				public void onFailure(Throwable caught) {
					System.out.println("Datastore could not remove " + group.groupName + " from " + CurrentUser.getInstance().getCurrentUserEmail() );
				}
				public void onSuccess(Void result) {
					System.out.println("Datastore removed " + group.groupName + " from " +  CurrentUser.getInstance().getCurrentUserEmail() + " successfully!");
				}          	
            });
        }
	}
}
